<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <!-- <el-form-item>
          <el-input v-model="filters.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getcustoms">查询</el-button>
        </el-form-item> -->
        <el-form-item style="float:right;">
          <el-button size="small" type="primary" v-show="roleAdd" icon="plus" @click="handleAdd">新增</el-button>
        </el-form-item>
        <!--  <el-form-item>
          <el-button type="primary" @click="export2Excel">导出</el-button>
        </el-form-item> -->
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="roles" stripe border :height='winHeight-188' highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column prop="roleid" label="角色ID" align="center" sortable>
      </el-table-column>
      <el-table-column prop="rolename" label="角色名" align="center" sortable>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" align="center" sortable>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center" :formatter="formatStatus" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" v-show="roleUpdate" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button type="primary" size="small" v-show="buttonShows(scope.$index, scope.row)" @click="handleRecover(scope.$index, scope.row)">恢复</el-button>
          <el-button type="danger" size="small" v-show="buttonShow(scope.$index, scope.row)" @click="handleDel(scope.$index, scope.row)">失效</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->
      <el-pagination style="float:right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="120px" :rules="addFormRules" ref="addForm">
        <el-row>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="角色名" prop="rolename">
              <el-input v-model="addForm.rolename" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="审批权限" prop="approveAuth">
              <el-select v-model="addForm.approveAuth" class="otherWidth" placeholder="是否显示">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="配置权限" prop="configAuth">
              <el-select v-model="addForm.configAuth" class="otherWidth" placeholder="是否显示">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="addForm.remarks" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色权限">
          <el-tree @check-change="addClickTree" :data="treedata" :props="defaultProps" ref="treeadd" show-checkbox node-key="id" default-expand-all :default-checked-keys="Adddefaultselected" :expand-on-click-node="false" :render-content="renderContent">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改" v-model="editFormVisible" @open="editShow" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
        <el-row>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="角色名" prop="rolename">
              <el-input v-model="editForm.rolename" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="审批权限" prop="approveAuth">
              <el-select v-model="editForm.approveAuth" class="otherWidth" placeholder="是否显示">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="配置权限" prop="configAuth">
              <el-select v-model="editForm.configAuth" class="otherWidth" placeholder="是否显示">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="16" :lg="12">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="editForm.remarks" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色权限">
          <el-tree @check-change="editClickTree" :data="treedata" :props="defaultProps" ref="treeedit" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultselected" :expand-on-click-node="false" :render-content="renderContent">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'

import commons from '../../common/js/common'
//import NProgress from 'nprogress'
import { mapState, mapActions } from 'vuex'
import { roleList, addAdmin, LdapUser, allMenuList, roleMenuList, setPermission, removeRole, addRole } from '../../api/api';
let id = 1000;
export default {
  data() {
    return {
      filters: {
        username: ''
      },
      roles: [],
      lists: [],
      total: 0,
      page: 1,
      pageSize: 10,
      treedata: [],
      listLoading: false,
      treeObj: '',
      sels: [],//列表选中列
      userid: '',
      defaultselected: [],//修改默认选中
      Adddefaultselected: [],
      editselected: [],
      editselecteds: [],
      addselected: [],
      addselecteds: [],
      editId: '',
      addFormVisible: false,//新增界面是否显示
      editFormVisible: false,//修改界面是否显示
      editLoading: false,
      IsFirst: true,
      addFormRules: {
        rolename: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        approveAuth: [
          { required: true, message: '请选择审批权限', trigger: 'blur' }
        ],
        configAuth: [
          { required: true, message: '请选择配置权限', trigger: 'blur' }
        ]
      },
      editFormRules: {
        rolename: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        approveAuth: [
          { required: true, message: '请选择审批权限', trigger: 'blur' }
        ],
        configAuth: [
          { required: true, message: '请选择配置权限', trigger: 'blur' }
        ]
      },
      //修改界面数据
      editForm: {
        rolename: '',
        power: [],
        roledata: [],
        approveAuth: '0',
        configAuth: '0',
        remarks: ''
      },
      detailFormVisible: false,//新增界面是否显示
      addLoading: false,
      IsShow: false,
      roleAdd: false,
      roleInvalid: false,
      roleRecovery: false,
      roleRemove: false,
      roleUpdate: false,

      //新增界面数据
      addForm: {
        rolename: '',
        power: [],
        approveAuth: '0',
        configAuth: '0',
        remarks: ''
      },
      roledata: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }

    }
  },
  computed: mapState([
    'winWidth',
    'winHeight'
  ]),
  methods: {
    formatStatus: function (row, column) {
      return row.status == '1' ? '有效' : (row.status == '0' ? '无效' : '');
    },
    buttonShow(index, row) {
      if (this.roleInvalid) {
        return row.status == "1" ? true : false;
      } else {
        return false;
      }
    },
    buttonShows(index, row) {
      if (this.roleRecovery) {
        return row.status == "0" ? true : false;
      } else {
        return false;
      }
    },
    renderContent(h, { node, data, store }) {
      return (
        <span>
          <span>
            <span>{node.label}</span>
          </span>
          <span style="float: right; margin-right: 20px">

          </span>
        </span>);
    },
    inquiry() {
      let para = new FormData();
      para.append("userId", this.addForm.userid);
      LdapUser(para).then((res) => {

        if (res.data.state == 0) {
          this.addForm.username = res.data.result.username;
          this.addForm.mobileno = res.data.result.mobileno;
          this.addForm.phoneno = res.data.result.phoneno;
          this.addForm.branchcode = res.data.result.branchcode;
          this.addForm.deptcode = res.data.result.deptcode;
          this.addForm.email = res.data.result.email;
          this.addForm.sex = res.data.result.sex;
          this.addForm.clevel = res.data.result.clevel;
          this.addForm.termcode = res.data.result.termcode;
          this.addForm.remarks = res.data.result.remarks;
        }
        else {
          this.$message({
            message: '未查到该用户的相关信息',
            type: 'error'
          })
        }
      });

    },
    handleCurrentChange(val) {
      this.page = val;
      this.getcustoms();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getcustoms();
    },
    editShow() {
      let _this = this;
      _this.$nextTick(function () {
        // _this.treeObj = this.$refs.treeedit;
        // _this.treeObj.setCheckedKeys([14]);
      });
    },
    //获取用户列表
    getcustoms() {
      let _this = this;
      _this.treedata = [];
      let para = new FormData();
      para.append("pageSize", this.pageSize);
      para.append("pageNumber", _this.page);
      para.append('type','');
      _this.listLoading = true;
      //NProgress.start();
      roleList(para).then((res) => {
        _this.total = res.data.result.totalElements;
        _this.roles = res.data.result.content;
        _this.lists = res.data.result.content;
        _this.listLoading = false;
        //NProgress.done();
      });
      allMenuList().then((res) => {
        var data = res.data.result;

        function gettree(arr, trees) {
          for (var i in arr) {
            if (arr[i].smenu) {
              trees.push({
                id: arr[i].menuid,
                label: arr[i].menuname,
                children: []
              });
              for (var k in arr[i].smenu) {
                if (arr[i].smenu[k].resid) {
                  trees[i].children.push({
                    id: arr[i].smenu[k].resid,
                    label: arr[i].smenu[k].resname,
                    resid: arr[i].smenu[k].resid
                  });
                }
              }
              if (!arr[i].smenu[0].resid) {
                gettree(arr[i].smenu, trees[i].children);
              }

            }

            else {
              trees.push({
                id: arr[i].menuid,
                label: arr[i].menuname
              });
            }
          }
        }
        gettree(data, _this.treedata);
      });
    },
    //详情
    dblclick(row, column, cell, event) {
      this.detailForm = row;
      this.detailForm.lastlogindate = commons.getDaytime(row.lastlogindate, 1);
      this.detailForm.logoutdate = commons.getDaytime(row.logoutdate, 1);
      this.detailForm.created = commons.getDaytime(row.created, 1);
      this.detailForm.disableddate = commons.getDaytime(row.disableddate, 1);
      this.detailForm.status = commons.userStaus(row.status);
      this.rowID = row.id;
      if (column.label == '用户名') {
        this.detailFormVisible = true;
      }
    },
    //恢复
    handleRecover: function (index, row) {
      this.$confirm('确认恢复该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let para = new FormData();
        para.append("roleId", row.roleid);
        para.append("type", "1");
        removeRole(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '恢复成功',
            type: 'success'
          });
          this.getcustoms();
        });
      }).catch(() => {
        this.listLoading = false;
      });
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认失效该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let para = new FormData();
        para.append("roleId", row.roleid);
        para.append("type", "0");
        removeRole(para).then((res) => {

          this.listLoading = false;
          if (res.data.success) {
            this.$message({
              message: '失效成功',
              type: 'success'
            });
            this.getcustoms();
          }
          else {
            this.$message({
              message: res.data.result,
              type: 'error'
            });
          }

        });
      }).catch(() => {
        this.listLoading = false;
      });
    },

    //table导出excel
    export2Excel: function () {
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../vendor/Export2Excel');
        const tHeader = ['用户ID', '用户名', '密码', '机构', '部门', '小组', '用户级别', '性别', '电话', '手机', '邮箱', '登陆次数', '最近登陆时间', '退出时间', '登陆IP', '备注', '创建日期', '创建人', '授权类型', '注销日期', '状态', '授权级别'];
        const filterVal = ['userid', 'username', 'password', 'branchcode', 'deptcode', 'termcode', 'clevel', 'sex', 'phoneno', 'mobileno', 'email', 'loginnum', 'lastlogindate', 'logoutdate', 'loginip', 'remarks', 'created', 'creater', 'authtype', 'disableddate', 'status', 'authLevel'];
        const list = this.lists;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '用户列表excel');
      })
    },
    formatJson: function (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    //显示修改界面
    handleEdit: function (index, row) {
      let _this = this;
      let list = new FormData();
      _this.powers = [];
      // var defaultdatas = [];
      _this.defaultselected = [];
      _this.editId = row.roleid;
      _this.editFormVisible = true;
      _this.editForm = Object.assign({}, row);
      list.append('roleId', row.roleid);
      function gettrees(arr, defaultdata) {
        for (var i in arr) {
          if (arr[i].smenu && arr[i].smenu.length > 0) {
            gettrees(arr[i].smenu, defaultdata);
          }
          else {
            try {
              if (arr[i].resid) {
                defaultdata.push(arr[i].resid);
              }
              else {
                defaultdata.push(arr[i].menuid);
              }

            }
            catch (err) {
              defaultdata.push(arr[i].menuid);
            }
          }
        }
      };
      roleMenuList(list).then((res) => {
        var data = res.data.result;
        gettrees(data, _this.defaultselected);
        _this.editselected = _this.defaultselected;
        this.$refs.treeedit.setCheckedKeys(_this.defaultselected);
      });

      _this.editForm.roledata = [];
    },
    //设置修改tree
    editClickTree: function (data, checked, indeterminate) {
      let _this = this;
      var IsHave = false;
      if (!data.children) {
        if (checked) {
          if (data.resid) {
            for (var i in _this.editselected) {
              if (_this.editselected[i] == data.id) {
                IsHave = true;
              }
            }
            if (!IsHave) {
              _this.editselected.push(data.id);
            }
          }
          else {
            _this.editselected.push(data.id);
          }
        }
        else {
          if (data.resid) {
            for (var i in _this.editselected) {
              if (_this.editselected[i] == data.id) {
                _this.editselected.splice(i, 1);
              }
            }
          }
          else {
            for (var i in _this.editselected) {
              if (_this.editselected[i] == data.id) {
                _this.editselected.splice(i, 1);
              }
            }
          }
        }
      }
    },
    //设置新增tree
    addClickTree: function (data, checked, indeterminate) {
      let _this = this;
      var IsHave = false;
      if (!data.children) {
        if (checked) {
          if (data.resid) {
            for (var i in _this.addselected) {
              if (_this.addselected[i] == data.id) {
                IsHave = true;
              }
            }
            if (!IsHave) {
              _this.addselected.push(data.id);
            }
          }
          else {
            _this.addselecteds.push(data.id);
          }
        }
        else {

          if (data.resid) {
            for (var i in _this.addselected) {
              if (_this.addselected[i] == data.id) {
                _this.addselected.splice(i, 1);
                i--;
              }
            }
          }
          else {
            for (var i in _this.addselecteds) {
              if (_this.addselecteds[i] == data.id) {
                _this.addselecteds.splice(i, 1);
                i--;
              }
            }
          }
        }
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.addFormVisible = true;
      this.addForm = {
        rolename: '',
        power: [],
        approveAuth: '0',
        configAuth: '0',
        remarks: ''
      };
      this.addselected = [];
      this.addselecteds = [];
      this.Adddefaultselected = [];
      try {
        this.$refs.treeadd.setCheckedKeys(this.Adddefaultselected);
      }
      catch (error) {

      }
    },
    //新增提交
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            var para = {
              roleName: this.addForm.rolename,
              approveAuth: this.addForm.approveAuth,
              remark: this.addForm.remarks,
              resids: this.addselected,
              fmenuIds: this.addselecteds,
              configAuth: this.addForm.configAuth
            };
            addRole(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getcustoms();
              // }

            });
          });
        }
      });
    },
    //修改
    editSubmit: function () {
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.editLoading = true;
        //NProgress.start();
        let para = {
          roleName: this.editForm.rolename,
          approveAuth: this.editForm.approveAuth,
          configAuth: this.editForm.configAuth,
          remark: this.editForm.remarks,
          roleId: this.editId,
          resids: this.editselected,
          fmenuIds: this.editselecteds,
        };
        setPermission(para).then((res) => {
          this.editLoading = false;
          //NProgress.done();
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          this.editFormVisible = false;
          this.getcustoms();
        });
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        // let para = { ids: ids };
        let para = new FormData();
        para.append("ids", ids);
        removeAd(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getcustoms();
        });
      }).catch(() => {

      });
    },
    btnShow: function () {
      let thisData = JSON.parse(sessionStorage.getItem('163'));
      let _this = this;
      $.each(thisData, function (i, j) {
        if (thisData[i] == "roleAdd") {
          _this.roleAdd = true;
        }
        if (thisData[i] == "roleInvalid") {
          _this.roleInvalid = true;
        }
        if (thisData[i] == "roleRecovery") {
          _this.roleRecovery = true;
        }
        if (thisData[i] == "roleRemove") {
          _this.roleRemove = true;
        }
        if (thisData[i] == "roleRemove") {
          _this.roleRemove = true;
        }
        if (thisData[i] == "roleUpdate") {
          _this.roleUpdate = true;
        }
      });
    },
  },
  mounted() {
    this.btnShow();
    this.getcustoms();
    this.editFormVisible = true;
    this.editFormVisible = false;
  }
}

</script>

<style scoped>

</style>